package Autodesk;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.hadoop.fs.Path;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import DatabaseManaging.JdbcChannelsDao;
import DatabaseManaging.JdbcCountriesDao;
import DatabaseManaging.JdbcLanguageDao;
import DatabaseManaging.JdbcProductsDao;
import DatabaseManaging.ParametersDAO;

public class Parser {
	
	public String getDay(String sday){ //01->1
		String result="";
		String days[]={"01","02","03","04","05","06","07","08","09"};
		int i=0;
		boolean daymatched=false;
		while(i<days.length && !(daymatched=days[i].equals(sday)) ){
			++i;
		}
		if(daymatched){
			result=Integer.toString(i+1);
		}else{
			result=sday;
		}
		return result;
	}

	public Map<ArrayList<String>,String> getStaticList(String param){
		ApplicationContext context = new ClassPathXmlApplicationContext("application-context-persist.xml");
		ParametersDAO dao=null;
		if("language".equals(param)){
			dao=(JdbcLanguageDao) context.getBean("JdbcLanguagesDao");
		}else if(("product").equals(param)){
			dao=(JdbcProductsDao) context.getBean("JdbcProductsDao");
		}else if(("channel").equals(param)){
			dao=(JdbcChannelsDao) context.getBean("JdbcChannelsDao");
		}else if(("country").equals(param)){
			dao=(JdbcCountriesDao) context.getBean("JdbcCountriesDao");
		}
		return dao.getMapwithAllElements();
	}
	public void getStaticList(Path patternFile,Map<ArrayList<String>,String> staticList,String param){
		try{
			BufferedReader fis=new BufferedReader(new FileReader(patternFile.toString()));	
			String pattern=null;
			
			while((pattern =fis.readLine())!=null){ //We consider that the input mapping product document is: ID-ProdAb/1/2/3/4/5 - ReleaseAb
				String record[] = pattern.split("\t");
				if(param.equals("products")){ 
					int i=1;
					ArrayList<String> abbProduct=new ArrayList<String>();
					while(i<record.length){
						if(!record[i].equals("")){
							abbProduct.add(record[i].toLowerCase());
						}
						i++;
					}
	//				abbProduct.add(record[record.length-1]); //The end of the list is the release abbreviation
					staticList.put(abbProduct,record[0]);
				}else{//We consider that the input mapping channel/language document is: ID-ProdName-ProdAb-/1/2/3/4/5
					int i=1;
					ArrayList<String> abbMatcher=new ArrayList<String>();
					while(record.length>i){
						abbMatcher.add(record[i].toLowerCase());
						i++;
					}
					staticList.put(abbMatcher,record[0]);
				}
			}
			fis.close();
		}catch(IOException ioe){
	         System.err.println("Caught exception while parsing the cached file '");
		}
	}
	public String lookForKey(Map<ArrayList<String>,String> staticList,String logkey,String param){
		boolean found=false;
		String logkey2=null;
		String id="1";
		Iterator it = staticList.keySet().iterator();
		while(it.hasNext() & !found) {	
			ArrayList<String> keyList = (ArrayList<String>) it.next();
			for(int i=0;i<keyList.size() & !found;i++){
				String gotList=keyList.get(i).toLowerCase();
				logkey2=logkey.toLowerCase();
				if(param.equals("ip")){
					int range=gotList.indexOf("%");
					if(range>-1 && logkey2.length()>range){
						gotList=gotList.substring(0, range);
						logkey2=logkey2.substring(0, range);
					}	
				}
				if(logkey2.equals(gotList)){
					id=staticList.get(keyList);
					found=true;
				}
			}
		}
		return id;
	}
	
	public String lookForKeyProduct(Map<ArrayList<String>,String> staticList,String product,String release){
		boolean found=false;
		String id="1";
		Iterator it = staticList.keySet().iterator();
		while(it.hasNext() & !found) {	
			ArrayList<String> keyList = (ArrayList<String>) it.next();
			for(int i=0;i<keyList.size() & !found;i++){				
				if(product.toLowerCase().equals((String)keyList.get(i).toLowerCase())){
					for(int f=0;f<keyList.size() & !found;f++){
						if(release.equals("all")){
							if(release.equals(keyList.get(f))){
								found=true;
								id=staticList.get(keyList);
							}
						}else{
							if(getYear(release).equals( getYear(keyList.get(f))) ){
								found=true;
								id=staticList.get(keyList);
							}
						}

					}
				}
			}
			
		}
//		System.out.println(id);
		return id;
	}
	
	private String getYear(String value){
		String year="";
		Pattern yearPattern = Pattern
				.compile("20[0-9][0-9]");
		Matcher yearMatcher = yearPattern.matcher(value);
		year = yearMatcher.find() ? yearMatcher.group() : value;
		return year;
	}


public String getChannel(String line) {
	String channel;
	Pattern channelPattern = Pattern.compile("project=[\\w\'-]*|[/]resource[/][a-zA-Z0-9]*[/]");

	Matcher channelMatcher = channelPattern.matcher(line);
	channel = channelMatcher.find() ? channelMatcher.group() : "";
	if (!channel.equals("") && channel.indexOf("project=") > -1)
		channel = channel.substring(channel.indexOf("=") + 1);
	else if (!channel.equals("") && channel.indexOf("/resource/") > -1)
		channel = channel.substring(channel.indexOf("/",
								channel.indexOf("/resource/") + 1) + 1,
						channel.lastIndexOf("/"));
	return channel;
}

public String getIp(String line) {
	Pattern ipPattern = Pattern
			.compile("[0-9]{1,4}[.][0-9]{1,4}[.][0-9]{1,4}[.][0-9]{1,4}");
	Matcher ipMatcher = ipPattern.matcher(line);
	String ip = ipMatcher.find() ? ipMatcher.group() : "";
	return ip;
}

public String getIpHaProxy(String line) {
	String ip;
	Pattern ipPattern = Pattern
			.compile("[0-9]{1,4}[.][0-9]{1,4}[.][0-9]{1,4}[.][0-9]{1,4}:[0-9]{1,4}");
	try{
		Matcher ipMatcher = ipPattern.matcher(line);
		ip = ipMatcher.find() ? ipMatcher.group() : "2";
		if(!ip.equals("2")){
			ip=ip.substring(0,ip.indexOf(':'));
		}
	}catch(Exception e){
		ip="2";
	}
	return ip;
}
public String getDate(String line){
	String date = null;
	String year = null;
	String month = null;
	String day = null;
	String dateMapper = "0";
	try{
		Pattern datePattern = Pattern
				.compile("[0-9]{4}[-][0-1][0-9][-][0-3][0-9]");
		Matcher dateMatcher = datePattern.matcher(line);
		while (dateMatcher.find()) {
			date = dateMatcher.group();
			if (date != null) {
				StringTokenizer datetokenizer = new StringTokenizer(date, "-");
				while (datetokenizer.hasMoreTokens()) {
					String token = datetokenizer.nextToken();
					if (year == null)
						year = token;
					else if (month == null)
						month = token;
					else if (day == null)
						day = token;
					else
						break;
				}
				dateMapper = year+month+day;
				//dateMapper = year +getDay(month)+ getDay(day);
			}
		}
	}catch(Exception e){
		//Problem with the IP
	}
return dateMapper;
}
public String getDateHaProxyLogs(String line){
	String dateMapper = "";
	try{
	line=line.substring(line.indexOf(" [")+2);
	line=line.substring(0,line.indexOf(':'));
	String[] tokenDate=line.split("/");
	String year=tokenDate[2];
	String day=tokenDate[0];
	String month=tokenDate[1];
	month=this.getMonth(month);
	dateMapper=year+month+day;
	}catch(StringIndexOutOfBoundsException e){
		dateMapper="0";
		System.out.println("Couldn't get date");
	}catch(java.lang.ArrayIndexOutOfBoundsException e2){
		dateMapper="0";
	}
	return dateMapper;
}

private String getMonth(String month) {
	String months[]={"jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"};
	int i=0;
	for(i=0;i<months.length  & !(months[i].equals(month.toLowerCase()));i++);
	return this.changeFormatMonth(i+1);
}
private String changeFormatMonth(int i){
	String result=Integer.toString(i);
	if(i>0 & i<10){
		result='0'+result;
	}
	return result;			
}

public String getHour(String line) {
	String hour = "";
	Pattern hourPattern = Pattern
			.compile("[0-2][0-9][:][0-5][0-9][:][0-5][0-9]");
	//String st=line.substring(0,line.indexOf("["));
	Matcher hourMatcher = hourPattern.matcher(line);
	hour = hourMatcher.find() ? hourMatcher.group() : "2";
	return hour;
}

public String getQueryLine(String line){
	String queryLine = "";
	try{
		queryLine = line.substring(line.indexOf("?") + 1);
		if(queryLine.indexOf("&_")>-1){
			queryLine = queryLine.substring(0,queryLine.indexOf("&_"));
		}else if( (queryLine.indexOf("\t")>-1) & (queryLine.indexOf("\t")<queryLine.indexOf(" ")) ){
			queryLine = queryLine.substring(0,queryLine.indexOf("\t"));
		}else{
			queryLine = queryLine.substring(0,queryLine.indexOf(" "));
		}
	}catch(StringIndexOutOfBoundsException e){
		queryLine=line;
	}
	return queryLine;
}

public String getCountry(String line){
	String result="1";
	if(line.indexOf("excntry=")>-1){
		//line = line.substring(line.indexOf("X-Query-Result=") + 15,line.indexOf("X-Forwarded-For="));
		line = line.substring(line.indexOf("excntry=") + 8);
		while(line.substring(0,1).equals("\"")){
			line=line.substring(1);
		}
		result = line.substring(0,2);
		if(result.equals("")){
			result="1";
		}
	}
	return result;
}

public ArrayList<String> getListIPForwaredFor(String line){
	ArrayList<String> result=new ArrayList<String>();
	if(line.indexOf("x-forwarded-for=")>-1){
		line = line.substring(line.indexOf("x-forwarded-for=") + 16);
		if(line.indexOf("\"")>-1){
		line = line.substring(0,line.indexOf("\""));
		}
		if(line.indexOf(",")>-1){
			String[] recordIP= line.split(", ");
			for(int i=0;i<recordIP.length;i++){				
				result.add(recordIP[i]);
			}
		}
	}
	return result;
}

	public String getProduct(String token, String queryLine, Parser par)
			throws UnsupportedEncodingException,StringIndexOutOfBoundsException  {
		String tokenProd = token.substring(2);
		tokenProd = URLDecoder.decode(tokenProd, "UTF-8");
		StringTokenizer tokenizer2 = new StringTokenizer(queryLine, "&");
		while ((tokenizer2.hasMoreTokens()) & (token.indexOf("v=") < 0)) {// We																// token.
			token = tokenizer2.nextToken();
		}
		String tokenRele = "";
		if ((token.indexOf("v=") > -1)) {
			tokenRele = token.substring(2);
		}
		tokenRele = URLDecoder.decode(tokenRele, "UTF-8");

		if (tokenRele.equals("") || tokenRele.equals("Help") || tokenRele.equals("help")) {
			tokenRele = "all";
		}
		String prodAb = tokenProd + "\t" + tokenRele;
		return prodAb;
//		if ((tokenRele.indexOf("<") > -1)) {
//			while (tokenRele.indexOf("<") > -1) {
//				tokenRele = tokenRele.substring(tokenRele.indexOf(">") + 1,
//						tokenRele.lastIndexOf("</"));
//			}
//		} else if (tokenRele.equals("") || tokenRele.equals("Help") || tokenRele.equals("help")) {
//			tokenRele = "all";
//		}

	}

}
